from pathlib import Path
from typing import Optional


try:
    import cv2  # type: ignore
except Exception:  # pragma: no cover - optional dependency
    cv2 = None  # type: ignore


_cascade = None


def _get_cascade():
    global _cascade
    if _cascade is not None:
        return _cascade
    if cv2 is None:
        return None
    try:
        cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"  # type: ignore[attr-defined]
        _cascade = cv2.CascadeClassifier(cascade_path)
        if _cascade.empty():
            _cascade = None
    except Exception:
        _cascade = None
    return _cascade


def detect_people_in_image(image_path: Path) -> bool:
    """检测图片中是否有人脸，返回布尔值。

    若 OpenCV 或级联分类器不可用，则返回 False（不影响主流程）。
    """
    if cv2 is None:
        return False
    cascade = _get_cascade()
    if cascade is None:
        return False
    try:
        img = cv2.imread(str(image_path))
        if img is None:
            return False
        # 降采样以提升嵌入设备性能
        height, width = img.shape[:2]
        scale = max(1, int(max(width, height) / 640))
        if scale > 1:
            img = cv2.resize(img, (width // scale, height // scale))
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)
        faces = cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4, minSize=(40, 40))
        return len(faces) > 0
    except Exception:
        return False


